package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.SeckillRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Setter
@Getter
public class InitSeckillProductJob implements SimpleJob {
    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;

    @Override
    public void execute(ShardingContext shardingContext) {
        doWork(shardingContext);
    }

    private void doWork(ShardingContext shardingContext) {
        // 查询秒杀商品信息
        String type = shardingContext.getShardingParameter();
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.listByType(Integer.parseInt(type));
        // 初始化到redis中
        if (!result.hasError()) {
            // 初始化vo对象
            List<SeckillProductVo> data = result.getData();
            data.forEach(s -> redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_PRODUCT_LIST.getRealKey(type), s.getId() + "", JSON.toJSONString(s)));
            // 初始化库存
            data.forEach(s -> redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(type), s.getId() + "", s.getStockCount() + ""));
        }
        System.out.println("初始化完成");
    }
}
